﻿using ETModel;
using System;
using System.Threading;
using UnityEngine;

namespace ETHotfix {
	[ObjectSystem]
	public class MoveComponentUpdateSystem : UpdateSystem<MoveComponent>
	{
		public override void Update(MoveComponent self)
		{
			self.Update();
		}
	}

    /// <summary>
    /// 平滑移动,附加给Unit即可使用
    /// </summary>
	public class MoveComponent : Component
	{
        protected Vector3 Target;

        // 开启移动协程的时间
        protected long StartTime;

		// 开启移动协程的Unit的位置
		protected Vector3 StartPos;

        protected long needTime;
		
		protected ETTaskCompletionSource moveTcs;


		public void Update()
		{
			if (this.moveTcs == null)
			{
				return;
			}
			
			Unit unit = this.GetParent<Unit>();
            long elapsedTime = TimeHelper.Now() - this.StartTime;

            if (elapsedTime >= this.needTime)
			{
                //本次移动耗时已经超过了总需要的时间,直接设置到目标,并且异步完成
				unit.Position = this.Target;
				ETTaskCompletionSource tcs = this.moveTcs;
				this.moveTcs = null;
				tcs.SetResult();
				return;
			}

			float amount = elapsedTime * 1f / this.needTime;//按本次耗时占需要耗时的比例进行插值
			unit.Position = Vector3.Lerp(this.StartPos, this.Target, amount);
		}

		public ETTask MoveToAsync(Vector3 target, float speedValue, CancellationToken cancellationToken)
		{
			
			if ((target - this.Target).magnitude < 0.1f)
			{
				return ETTask.CompletedTask;
			}
			
			this.Target = target;

            Unit unit = this.GetParent<Unit>();

            this.StartPos = unit.Position;
			this.StartTime = TimeHelper.Now();
			float distance = (this.Target - this.StartPos).magnitude;
			if (Math.Abs(distance) < 0.1f)
			{
				return ETTask.CompletedTask;
			}
            
			this.needTime = (long)(distance / speedValue * 1000);
			
			this.moveTcs = new ETTaskCompletionSource();
			
			cancellationToken.Register(() =>
			{
				this.moveTcs = null;
			});
			return this.moveTcs.Task;
		}
	}
}